/*
 * @Author: Wangtao
 * @Date: 2021-03-18 13:42:21
 * @LastEditors: Wangtao
 * @LastEditTime: 2021-03-26 18:03:41
 */
import { Component, Vue } from 'vue-property-decorator'
import { IvrModule } from '@/store/modules/config/ivr'
import { ElMessage } from 'element-ui/types/message'
import { CtiModule } from '@/store/modules/cti/index'

@Component({
  name: 'task-mixin',
  filters: {
    getTaskStatus (item) {
      let text = '未知状态'
      switch (item.status) {
        case 'READY':
          text = '未开启'
          break;
        case 'DEALING':
          text = '执行中'
          break;
        case 'PAUSED':
          text = '已暂停'
          break;
        case 'CLOSE':
          text = '已完成'
          break;
        case 'ARCHIVED':
          text = '已归档'
          break;
        default:
          break;
      }
      return text
    }
  }
})

export default class extends Vue {
  public $bus: any
  public $message: undefined | ElMessage
  public $store: any

  get account () {
    return (this.$store as any).state.common.session.account._id
  }

  get userId () {
    return (this.$store as any).state.common.session.user._id
  }

  get agentNumber () {
    return (this.$store as any).state.common.session.user.agentNumber
  }

  get loginToken () {
    return (this.$store as any).state.common.session.user.loginToken
  }

  get isCalling () {
    return CtiModule.isCalling
  }

  /**
   * 执行率
   * @param row.called {number} 拨打数量
   * @param row.total {number} 任务数量
   * @returns {number}
   */
  public getProcess (row: any): number {
    const num = parseFloat(row.called);
    const total = parseFloat(row.total);
    if (isNaN(num) || isNaN(total)) {
      return 0
    }
    return total <= 0 ? 0 : (Math.round(num / total * 10000) / 100.00)
  }

  public getFormat (row: any) {
    return row.called + '/' + row.total
  }

  /**
   * 接通率
   * @param row.dealing {number} 接听数量
   * @param row.total {number} 拨打数量
   * @returns {number}
   */
  public getConnectionRate (row: any) {
    const num = parseFloat(row.dealing);
    const total = parseFloat(row.callout);
    if (isNaN(num) || isNaN(total)) {
      return '-'
    }
    return total <= 0 ? 0 : (Math.round(num / total * 10000) / 100.00)
  }

  /**
   * 删除任务
   * @param _id {string} 任务id
   * @return {promise}
   */
  public handleDelete (id: string) {
    return new Promise((resolve, reject) => {
      const tipText = '删除'
      const query = { _id: id }
      const data = { url: '/call/action/task/delete', method: 'POST', data: query }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success) {
          (this.$message as ElMessage).success(`${tipText}成功`)
          resolve(true)
        } else {
          resolve(false)
        }
      })
    })
  }

  /**
   * 更新任务状态
   * @param id {string} 任务id
   * @param status {string} 更新的状态
   * @return {promise}
   */
  public updateTaskState (id: string, status: string) {
    return new Promise((resolve) => {
      let tipText = ''
      const query = { _id: id, status }
      const data = { url: '/call/action/task/changeStatus', method: 'POST', data: query }
      if (status === 'READY' || status === 'DEALING') {
        tipText = '开启'
      }
      if (status === 'PAUSED') {
        tipText = '暂停'
      }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success) {
          (this.$message as ElMessage).success(`${tipText}成功`);
          resolve(true)
        }
      })
    })
  }

  public handleSetTabelHeight () {
    this.$nextTick(() => {
      (this.$refs as any).configTabel.handleSetTabelHeight()
    })
  }

  public taskDialot (taskId, phone, previewNumberId?: string) {
    this.getNextDialoutStatus(taskId).then((status) => {
      if (status) {
        const calleeNumber = phone
        if (!calleeNumber) {
          (this.$message as any)({ message: '号码为空', type: 'error' });
        }
        if (!taskId) {
          (this.$message as any)({ message: '任务id异常', type: 'error' });
        }
        const sendData: any = { calleeNumber, taskId }
        if (previewNumberId) {
          sendData.previewNumberId = previewNumberId
        }
        CtiModule.CtiDialoutAction(sendData).then((dialoutRes: any) => {
          if (dialoutRes && dialoutRes.success) {
            this.$emit('screen');
            (this.$message as any)({ message: '外呼成功', type: 'success' });
          }
        })
      } else {
        (this.$message as any)({ message: '当前任务无法执行', type: 'error' });
      }
    })
  }

  public getNextDialoutStatus (taskId: string) {
    return new Promise((resolve) => {
      const actionData = Object.assign({ _id: taskId })
      const data = { url: '/call/action/task/search', method: 'POST', data: actionData }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success) {
          if (res.data && res.data.status === 'DEALING') {
            resolve(true)
          } else {
            resolve(false)
          }
        } else {
          resolve(false)
        }
      })
    })
  }

  /**
   * 根据任务id获取任务数据
   * @param taskId {string} 任务id
   * @param userId {string} 座席id
   */
  public getTaskInfoById (taskId: string, userId: string) {
    return new Promise((resolve) => {
      const actionData = Object.assign({ taskId, user: userId })
      const data = { url: '/call/action/task/user/info', method: 'POST', data: actionData }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success && res.data) {
          resolve(res.data)
        }
      })
    })
  }
}
